/**
 * 储存文件到指定的地址:把一个文件移动到另外一个位置 剪切文件 重命名文件
 * @param {String} url				 	新的地址 _doc/ 开头
 * @param {String} file                	原文件地址
 * @param {String} newfilename 			新的文件名
 */
async function saveFile(url, file, newfilename) {
	let c = await creatDirs(url)
	let isokm = moveDirectyOrFile(file, url + "/", newfilename);
	return isokm
}

// 循环创建目录 url:"_doc/...."  _doc开头
async function creatDirs(url) {
	let urllist = url.split("/");
	console.log(urllist)
	//创建文件夹
	let u = "";
	for (let i = 0; i < urllist.length - 1; i++) {
		let j = i;
		if (i == 0) {
			u = urllist[i];
		} else {
			u = u + "/" + urllist[i];
		}
		console.log(i + "-------------------")
		console.log(u)
		console.log(urllist[j + 1])
		await CreateNewDir(u, urllist[j + 1]);
	}
}

// 重命名目录或文件名
function moveDirectyOrFile(srcUrl, dstUrl, newName) { //srcUrl需要移动的目录或文件，dstUrl要移动到的目标目录（父级）
	plus.io.resolveLocalFileSystemURL(srcUrl, function(srcEntry) {
		//console.log(111)
		plus.io.resolveLocalFileSystemURL(dstUrl, function(dstEntry) {
			//console.log(222)
			if (srcEntry.isDirectory) {
				//console.log(33)
				srcEntry.moveTo(dstEntry, newName, function(entry) {
					//console.log("New Path: " + entry.fullPath);
					return true;
				}, function(e) {
					return e;
					//console.log(e.message);
				});
			} else {
				srcEntry.moveTo(dstEntry, newName, function(entry) {
					//console.log("New Path: " + entry.fullPath);
					return true;
				}, function(e) {
					return e;
					//console.log(e.message);
				});
			}
		}, function(e) {
			uni.showToast({
				title: '获取目标目录失败:' + e.message,
				duration: 2000,
				icon: 'none'
			});
		});
	}, function(e) {
		uni.showToast({
			title: '获取目录失败:' + e.message,
			duration: 2000,
			icon: 'none'
		});
	});
}

// 创建一个新目录
function CreateNewDir(url, dirName) {
	//url值可支持相对路径URL、本地路径URL
	return new Promise((resolver, reject) => {
		plus.io.resolveLocalFileSystemURL(url, function(entry) {
			entry.getDirectory(dirName, {
				create: true,
				exclusive: false
			}, function(dir) {
				resolver(true)
			}, function(error) {
				reject(error.message)
				uni.showToast({
					title: dirName + '目录创建失败:' + error.message,
					duration: 2000,
					icon: 'none'
				});
			});
		}, function(e) {
			reject(error.message)
			uni.showToast({
				title: '获取目录失败:' + e.message,
				duration: 2000,
				icon: 'none'
			});
		});
	})
}

/**
 * 获取文件数据
 * @param {String} url 文件路径，最好是相对路径 url:"_doc/...."  _doc开头
 */
function getFileContext(url) {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(url, (entry) => {
			if (entry.isFile) {
				entry.file(function(file) {
					console.log(file);
					const fileReader = new plus.io.FileReader();
					console.log("getFile:" + JSON.stringify(file));
					fileReader.onload = function(evt) {
						console.log(evt);
						resolve(evt.target)
					}
					fileReader.readAsText(file, 'utf-8');
				});
			} else {
				reject('错误：路径必须是文件')
				uni.showModal({
					title: "错误",
					content: "路径必须是文件"
				})
			}
		}, (e) => {
			reject(e)
			// uni.showModal({
			// 	title: "错误",
			// 	content: "打开文件系统时出错"
			// })
		})
	})
}

/**
 * 复制文件
 * @param {String} url        文件地址，文件路径，最好是相对路径 url:"_doc/...."  _doc开头
 * @param {String} newUrl     目标目录，最好是相对路径 url:"_doc/...."  _doc开头
 * @param {String} newName    拷贝后的文件名称，默认为原始文件名称
 */
function copyFileTo(url, newUrl, newName) {
	let len = arguments.length;
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(url, async (entry) => {
			if (entry.isFile) {
				let c = await creatDirs(newUrl)
				let u = await getDirsys(newUrl)
				if (len == 3) {
					entry.copyTo(u, newName, en => {
						console.log(en);
						resolve(en)
					}, e => {
						console.log(e);
						reject('错误：复制时出现错误')
						uni.showModal({
							title: "错误",
							content: "复制时出现错误"
						})
					})
				} else {
					entry.copyTo(u, "", en => {
						console.log(en);
						resolve(en)
					}, e => {
						console.log(JSON.stringify(e));
						reject('错误：复制时出现错误')
						uni.showModal({
							title: "错误",
							content: "复制时出现错误"
						})
					})
				}


			} else {
				reject('错误：路径必须是文件')
				uni.showModal({
					title: "错误",
					content: "路径必须是文件"
				})
			}
		}, (e) => {
			console.log(e);
			reject(e)
			uni.showModal({
				title: "错误",
				content: "打开文件系统时出错"
			})
		});
	})
}

/**
 * 根据条件，获取目录中包含的文件及子目录
 * @param {Object} params {	url：指定的目录,
 * 							type：要列出的是文件file，还是目录dir，还是所有all,
 * 							regex：正则表达式，根据文件或者目录的名称进行筛选
 *  					  }
 * @return {Promise} 返回 列表Array
 */
async function getDirList(params) {
	let url = params.url ?? "_doc"
	let type = params.type ?? "all"
	let regex = params.regex ?? new RegExp("")

	const d = await getDirsys(url)
	return new Promise((resolve, reject) => {
		d.createReader().readEntries(entries => {
			let result = []
			for (let i = 0; i < entries.length; i++) {
				let a = {
					url: entries[i].fullPath,
					name: entries[i].name
				}

				switch (params?.type) {
					case "file": {
						if (entries[i].isFile == true && regex.test(entries[i].name)) {
							result.push(a)
						}
						break;
					}

					case "dir": {
						if (entries[i].isDirectory == true && regex.test(entries[i].name)) {
							result.push(a)
						}
						break;
					}

					case "all": {
						if (regex.test(entries[i].name)) {
							result.push(a)
						}
						break;
					}

					default: {
						if (regex.test(entries[i].name)) {
							result.push(a)
						}
						break;
					}


				}
			}
			// let ul = entries.filter(e=>e.isFile == true)
			// let result = ul.map(e=>{
			// 	return {
			// 		url:e.fullPath,
			// 		name:e.name
			// 	}
			// })
			resolve(result)
		}, e => {
			reject(e)
			uni.showModal({
				title: "错误",
				content: "Read entries failed: " + e.message
			})
		})
	})

}

// 删除目录或者文件，如果是目录，将会删除其下的所有文件及子目录
async function remove(url) {
	const d = await getDirsys(url)
	return new Promise((resolve, reject) => {
		if (d.isDirectory) {
			//删除目录将会删除其下的所有文件及子目录 不能删除根目录，如果操作删除根目录将会删除目录下的文件及子目录，不会删除根目录自身
			d.removeRecursively(() => {
				resolve("删除成功")
			}, e => {
				console.log(e);
				uni.showModal({
					title: "删除时错误",
					content: e.message
				})
			})
		}
		if (d.isFile) {
			d.remove(() => {
				resolve("删除成功")
			}, e => {
				console.log(e);
				uni.showModal({
					title: "删除时错误",
					content: e.message
				})
			})
		}
	})
}

/**
 * 写数据
 * @param {Object} url 创建文件的路径，必须是已经存在的路径
 * @param {Object} filename 文件名
 */
function writeFile(url,filename,str) {
	return new Promise((resolve,reject)=>{
		plus.io.requestFileSystem(url, function(fs) {
			// 可通过fs进行文件操作 
			console.log("Request file system success!");
			console.log(fs.name);
			fs.root.getFile(
				filename, {
					create: true,
					exclusive: false
				},
				fileEntry => {
					fileEntry.createWriter(
						writer => {
							writer.onwrite = e => {
								console.log(e.target.fileName);
								resolve(e)
								// setTimeout(function() {
								// 	// that.proshow = false;
								// 	uni.openDocument({
								// 		filePath: `file://${e.target.fileName}`, //这里必须加file://否则会报错打不开文件
								// 		success: function(res) {
								// 			console.log(res);
								// 			resolve(res)
								// 		},
								// 		fail(res) {
								// 			console.log(res);
								// 			reject(res)
								// 		}
								// 	});
								// }, 1000);
							};
							writer.write(str);
						},
						function(e) {
							uni.showToast({
								title: '导出文件失败，请检查你的权限',
								icon: 'none'
							});
							reject(e)
						}
					);
				},
				e => {
					console.log(e);
					reject(e)
				}
		
			);
		
		}, function(e) {
			reject(e)
		});
	})

}

// 获取目录对象
function getDirsys(url) {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(url, (entry) => {
			resolve(entry)
		}, (e) => {
			reject(e)
			console.log(e);
		});
	})
}

// 读取内容
function readData (callback) {
  callback = callback || function () {}
  plus.io.requestFileSystem( plus.io.PRIVATE_DOC, function( fs ) {
    // fs.root是根目录操作对象DirectoryEntry
    // console.log("url="+fs.toURL())
    fs.root.getFile('db.txt', { create: true }, function(fileEntry) {
      fileEntry.file( function(file){
        // console.log(file.size + '--' + file.name)
        var fileReader = new plus.io.FileReader()
        // console.log("getFile:" + JSON.stringify(file))
        fileReader.readAsText(file, 'utf-8')
        fileReader.onloadend = function(evt) {
          let data = ''
          var result = evt.target.result
          if(result !== '' && /\{|\[/.test(result)) {
            try {
              let json = JSON.parse(result)
              data = json
            } catch (e) {
              data = result
            }
          }
          callback({ state: 1, message:"读取成功！", data: data })
        }
      })
    })
  }, function ( e ) {
    callback({ state: -1, message: e.message })
  })
}

// 写入内容
function writeData (data, callback) {
  callback = callback || function () {}
  plus.io.requestFileSystem( plus.io.PRIVATE_DOC, function(fs) {
    // fs.root是根目录操作对象DirectoryEntry
    // console.log("url="+fs.toURL());
    fs.root.getFile('db.txt', { create: true }, function(fileEntry) {
      fileEntry.createWriter( function ( writer ) {
        writer.onwrite = function (e) {
          console.log( "Write data success!" )
        }
        data = typeof data === 'object' ? JSON.stringify(data, null, '  ') : String(data)
        writer.seek(0)
        // var bb = new BlobBuilder()
        // bb.append(data)
        // writer.write(bb.getBlob('text/plain'))
        writer.write(data)
        callback({state: 1, message: "保存数据成功！"})
      }, function (e) {
        callback({ state: -1, message: e.message })
      })
    })
  }, function (e) {
    callback({ state: -1, message: e.message })
  })
}

// 清空内容
function clearData (callback) {
  writeData('', callback)
}

// 读取内容
function readContent (callback) {
  let pathUrl = '/_doc/db.txt'  //指定文件路径
  let environment = plus.android.importClass("android.os.Environment")
  var sdRoot = environment.getExternalStorageDirectory() //文件夹根目录
  var File = plus.android.importClass("java.io.File")
  var BufferedReader = plus.android.importClass("java.io.BufferedReader")
  var FileReader = plus.android.importClass("java.io.FileReader")
  var FileWriter = plus.android.importClass("java.io.FileWriter")
  let readFr = new File(sdRoot + pathUrl)
  let txt = ''
  try {  
    var reader = new BufferedReader(new FileReader(readFr))
    // 我的需求是读取多行,所以把每行都读出来存在数组里  
    let arr = []
    let txt
    while ((txt = reader.readLine()) !== null) {
      arr.push(txt)
    }
    // 传入回调处理你的业务
    callback({ state: 1, message:"读取成功！", data: txt })
    //处理业务逻辑
  } catch (e) {
    callback({ state: -1, message: e.message })
  }
}

export default {
	saveFile,
	creatDirs,
	moveDirectyOrFile,
	getFileContext,
	copyFileTo,
	getDirList,
	getDirsys,
	writeFile,
	remove,
  readData,
  writeData,
  clearData
}